﻿using AutoMapper;
using MediatR;
using MyMES.Domain.yjb;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Writer.API.Application.Commends.settingCommand;
using MyMES.Writer.API.FileNlog;

namespace MyMES.Writer.API.Application.CommendHandlers.settingCommand
{
    public class AddTBCommandHandlers : IRequestHandler<AddTBCommand, APIResult<TransferOrder>>
    {
        private readonly IBaseRepository<TransferOrder> accreop;
        private readonly IMapper mapper;
        private readonly Nolgs nlogs;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="accreop"></param>
        /// <param name="mapper"></param>
        /// <param name="nlogs"></param>
        public AddTBCommandHandlers(IBaseRepository<TransferOrder> accreop, IMapper mapper, Nolgs nlogs)
        {
            this.accreop = accreop;
            this.mapper = mapper;
            this.nlogs = nlogs;
        }
        /// <summary>
        /// 转移调拨添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<TransferOrder>> Handle(AddTBCommand request, CancellationToken cancellationToken)
        {
            var startTime = DateTime.Now;
            try
            {
                APIResult<TransferOrder> result = new APIResult<TransferOrder>();
                result.Code = APIEnum.添加成功;
                result.Msg = "添加成功";
                var model = mapper.Map<TransferOrder>(request);
                string sql = "insert into TransferOrder(TransferOrderId,TransferOrderNumber,IsAutoGenerate,TransferOrderName,TransferOrderType,TransferDate,IsDelivery,Consignee,ContactInformation,Carrier,TransportOrderNumber,Destination,Remarks,TransferOrderzt,IsDelete) values(@TransferOrderId,@TransferOrderNumber, @IsAutoGenerate, @TransferOrderName, @TransferOrderType, @TransferDate, @IsDelivery, @Consignee, @ContactInformation,@Carrier,@TransportOrderNumber,@Destination,@Remarks,@TransferOrderzt,@IsDelete)";
                await accreop.Insert(model, sql);
                return result;
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                var endTime = System.DateTime.Now;

                var durationInDays = (endTime - startTime).Days;
                nlogs.GetNlogs(
                    request.TransferOrderName ?? "Unknow", "仓库添加", "False", durationInDays, "异常信息"
                    );
            }
        }
    }
}
